<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2017/2/16
 * Time: 上午8:36
 */
namespace app\admin\controller;
include EXTEND_PATH."alipay/AopSdk.php";
use app\common\model\Settings;
use app\common\model\Pushlog;
use think\Controller;
use think\Exception;
use think\Log;
use think\Db;
use think\Loader;
use app\common\model\WeixinPay;
use app\admin\model\Wallet;
class PayNotify extends Controller
{

    public function weixin()
    {
        Log::log(file_get_contents("php://input"));
        $xml = file_get_contents('php://input');//获取微信返回来的通知

        //file_put_contents('./1.txt', $xml,FILE_APPEND);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);//解析数据

        if($arr=='')
        {
            $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
        }else{

            if($arr['result_code']=="SUCCESS")
            {
                /*去掉其中的sign*/
                $old_sign=$arr['sign'];
                foreach ($arr as $k=>$v)
                {
                    if($k=='sign')
                    {
                        unset($arr[$k]);
                    }
                }

                $weixin=new WeixinPay();
                $sign=$weixin->getSign($arr);//根据返回的数据签名，和返回的签名比较是否一样

                //验签名。默认支持MD5
                if ( $sign === $old_sign) {;
                    //file_put_contents('./1.txt', 'ceshi',FILE_APPEND);
                    //   校验返回的订单金额是否与商户侧的订单金额一致。修改订单表中的支付状态。
                    $order_info = db('order')
                        ->where('orderid', $arr['out_trade_no'])
                        ->find();
                    if($order_info&&$order_info['pay_status']==0){
                        //有此订单且未支付
                        $real_price = $order_info['money'];
                        $real_price = $real_price*100;
                        $real_price = intval($real_price);
                        if ($real_price != $arr['total_fee']) {

                            $return = ['return_code' => 'FAIL', 'return_msg' => '订单金额不对！'];
                            exit;
                        }

                        //微信支付-改为已支付
                        db('order')
                            ->where('id', $order_info['id'])
                            ->update(array(
                                'pay_time'=>time(),
                                'pay_status' => 1,
                                'pay_type'=>1
                            ));

                        if($order_info['order_type']==1){
                            //激活订单
                            $user=Db::name('user')
                                ->where('id',$order_info['uid'])
                                ->field('mobile,parent_id')
                                ->find();
                            /*系统参数*/
                            $setting=Settings::getSystem();
                            /*赠送自己*/
                            Wallet::addDelCoin($user['mobile'],$setting['activate_give'],1,'激活赠送自己H币！');
                            /*赠送上级*/
                            if($user['parent_id'])
                            {
                                $parent=Db::name('user')
                                    ->where('id',$user['parent_id'])
                                    ->field('mobile,parent_id')
                                    ->find();
                                Wallet::addDelCoin($parent['mobile'],$setting['activate_reward'],1,'下级激活赠送H币！');
                            }
                            /*修改状态*/
                            Db::name('user')
                                ->where('id',$user['id'])
                                ->update(array(
                                    'identity'=>2,
                                    'update_time'=>time()
                                ));
                            Db::name('order')
                                ->where('id',$order_info['id'])
                                ->update(array(
                                    'pay_status'=>1
                                ));
                        }else if($order_info['order_type']==2){
                            //活动订单
                            Db::name('order')
                                ->where('id',$order_info['id'])
                                ->update(array(
                                    'pay_status'=>1
                                ));
                            Db::name('order_comment')
                                ->insertGetId(array(
                                    'uid'=>$order_info['uid'],
                                    'order_id'=>$order_info['id'],
                                    'active_id'=>$order_info['active_id'],
                                    'union_id'=>$order_info['union_id'],
                                    'receive_uid'=>$order_info['receive_uid'],
                                    'star'=>5,
                                    'comment_type'=>1,
                                    'content'=>"默认好评",
                                    'comment_time'=>time()
                                ));
                        }else{
                            //3线下订单
                            Db::name('order')
                                ->where('id',$order_info['id'])
                                ->update(array(
                                    'pay_status'=>1
                                ));
                            Db::name('order_comment')
                                ->insertGetId(array(
                                    'uid'=>$order_info['uid'],
                                    'order_id'=>$order_info['id'],
                                    'active_id'=>$order_info['active_id'],
                                    'union_id'=>$order_info['union_id'],
                                    'receive_uid'=>$order_info['receive_uid'],
                                    'star'=>5,
                                    'comment_type'=>2,
                                    'content'=>"默认好评",
                                    'comment_time'=>time()
                                ));
                        }
                    }

                    $return = ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];
                }else{

                    $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
                }
            }else{
                $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
            }
        }


        $xml = '<xml>';
        foreach($return as $k=>$v){
            $xml.='<'.$k.'><![CDATA['.$v.']]></'.$k.'>';
        }
        $xml.='</xml>';

        echo $xml;
    }
    public function del_nopayorder($order_info){
        if($order_info['order_type']==1){
            $delcon['xqid'] = $order_info['xqid'];
            $delcon['tbid'] = $order_info['tbid'];
        }
        $delcon['order_type'] = $order_info['order_type'];
        $delcon['status'] = 0;
        $delcon['uid'] = $order_info['uid'];
        Db::name('order')->where($delcon)->delete();
    }

    /*支付宝回调*/
    public function ali()
    {
        /*获取全部返回结果*/
        if(!empty($_POST))
        {
//            file_put_contents("return_data.txt",json_encode($_POST),FILE_APPEND);
            if($_POST['trade_status']!='TRADE_SUCCESS')
            {
                echo "fail";die;
            }else{
                /*订单信息*/
                $order_info = db('order')
                    ->where('orderid', $_POST['out_trade_no'])
                    ->find();
                if($order_info['pay_status']==1)
                {
                    echo "success";die;
                }

                if(empty($order_info)||($order_info['money']!=$_POST['total_amount']))
                {
                    echo "fail";die;
                }
                else
                {
                    $aop=new \AopClient();
                    $aop->rsaPrivateKey = config('alipay.rsaPrivateKey') ;
                    $aop->alipayrsaPublicKey=config("alipay.alipayrsaPublicKey");

                    /*验签*/
                    $verify= $aop->rsaCheckV1($_POST, '','RSA2');

                    if(!$verify)
                    {
                        echo "fail";
                    }
                    //支付宝支付-改为已支付

                    if($order_info['order_type']==1){
                        //激活订单
                        $user=Db::name('user')
                            ->where('id',$order_info['uid'])
                            ->field('id,mobile,parent_id')
                            ->find();
                        /*系统参数*/
                        $setting=Settings::getSystem();
                        /*赠送自己*/
                        Wallet::addDelCoin($user['mobile'],$setting['activate_give'],1,'激活赠送自己H币！');
                        /*赠送上级*/
                        if($user['parent_id'])
                        {
                            $parent=Db::name('user')
                                ->where('id',$user['parent_id'])
                                ->field('id,mobile,parent_id')
                                ->find();
                            Wallet::addDelCoin($parent['mobile'],$setting['activate_reward'],1,'下级激活赠送H币！');
                        }
                        /*修改状态*/
                        Db::name('user')
                            ->where('id',$user['id'])
                            ->update(array(
                                'identity'=>2,
                                'update_time'=>time()
                            ));
                        Db::name('order')
                            ->where('id',$order_info['id'])
                            ->update(array(
                                'pay_status'=>1
                            ));
                    }else if($order_info['order_type']==2){
                        //活动订单
                        Db::name('order')
                            ->where('id',$order_info['id'])
                            ->update(array(
                                'pay_status'=>1
                            ));
                        Db::name('order_comment')
                            ->insertGetId(array(
                                'uid'=>$order_info['uid'],
                                'order_id'=>$order_info['id'],
                                'active_id'=>$order_info['active_id'],
                                'union_id'=>$order_info['union_id'],
                                'receive_uid'=>$order_info['receive_uid'],
                                'star'=>5,
                                'comment_type'=>1,
                                'content'=>"默认好评",
                                'comment_time'=>time()
                            ));
                    }else{
                        //3线下订单
                        Db::name('order')
                            ->where('id',$order_info['id'])
                            ->update(array(
                                'pay_status'=>1
                            ));
                        Db::name('order_comment')
                            ->insertGetId(array(
                                'uid'=>$order_info['uid'],
                                'order_id'=>$order_info['id'],
                                'active_id'=>$order_info['active_id'],
                                'union_id'=>$order_info['union_id'],
                                'receive_uid'=>$order_info['receive_uid'],
                                'star'=>5,
                                'comment_type'=>2,
                                'content'=>"默认好评",
                                'comment_time'=>time()
                            ));
                    }
                    echo "success";
                }
            }
        }else{
            echo "fail";
        }
    }
}